<template>
  <view class="area-picker">
    <picker
      mode="multiSelector"
      :value="pickerValue"
      :range="pickerRange"
      range-key="name"
      :disabled="disabled"
      @change="onPickerChange"
      @cancel="onCancel"
      @columnchange="onColumnChange"
    >
      <view class="picker-row" :class="{ 'picker-disabled': disabled }">
        <text class="picker-value" :class="{ 'placeholder': !displayText }">{{ displayText || placeholder }}</text>
        <image class="arrow" :src="arrowIcon" v-if="!disabled" />
      </view>
    </picker>
  </view>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRequest } from '@/api'
import { imgUrl } from '@/utils/config'
const { API_INDEX_AREA_POST } = useRequest()

// Props
const props = defineProps({
  // 占位符文本
  placeholder: {
    type: String,
    default: '请选择省市区'
  },
  // 箭头图标
  arrowIcon: {
    type: String,
    default: imgUrl + 'arrow-right.png'
  },
  // 默认选中的值
  defaultValue: {
    type: Object,
    default: () => ({})
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['change', 'cancel'])

// 响应式数据
const pickerValue = ref([0, 0, 0])
const pickerRange = ref([[], [], []])
const provinces = ref([])
const cities = ref([])
const districts = ref([])
const selectedProvince = ref(null)
const selectedCity = ref(null)
const selectedDistrict = ref(null)
const isLoadingCities = ref(false)
const isLoadingDistricts = ref(false)
const isLoadingProvinces = ref(false)

// 保存上一次默认值，避免无意义重复处理
const lastDefaultValue = ref({ province: null, city: null, district: null })

// 计算属性
const displayText = computed(() => {
  if (selectedProvince.value && selectedCity.value && selectedDistrict.value) {
    return `${selectedProvince.value.name} ${selectedCity.value.name} ${selectedDistrict.value.name}`
  }
  return ''
})

// 监听默认值变化（按值比较，避免父组件重渲染产生的新对象触发）
watch(
  () => props.defaultValue,
  async (newValue) => {
    if (!newValue) return
    const province = Number(newValue.province || 0)
    const city = Number(newValue.city || 0)
    const district = Number(newValue.district || 0)

    const changed =
      province && city && district &&
      (province !== lastDefaultValue.value.province ||
        city !== lastDefaultValue.value.city ||
        district !== lastDefaultValue.value.district)

    if (!changed) return

    lastDefaultValue.value = { province, city, district }
    await setDefaultSelection(lastDefaultValue.value)
  },
  { immediate: true, deep: false }
)

// 组件挂载时初始化数据
onMounted(async () => {
  initPickerData()
  await loadProvinces()
})

// 初始化picker数据结构
function initPickerData() {
  if (!Array.isArray(pickerRange.value)) {
    pickerRange.value = [[], [], []]
  }
  if (!Array.isArray(pickerValue.value)) {
    pickerValue.value = [0, 0, 0]
  }
  
  while (pickerRange.value.length < 3) {
    pickerRange.value.push([])
  }
  while (pickerValue.value.length < 3) {
    pickerValue.value.push(0)
  }
}

// 设置默认选中
async function setDefaultSelection(defaultValue) {
  try {
    // 确保省份列表仅加载一次
    if (provinces.value.length === 0) {
      await loadProvinces()
    }
    
    // 查找省份索引
    const provinceIndex = provinces.value.findIndex(p => p.value === defaultValue.province)
    if (provinceIndex === -1) return
    
    // 加载城市数据并查找索引
    await loadCities(defaultValue.province)
    const cityIndex = cities.value.findIndex(c => c.value === defaultValue.city)
    if (cityIndex === -1) return
    
    // 加载区县数据并查找索引
    await loadDistricts(defaultValue.province, defaultValue.city)
    const districtIndex = districts.value.findIndex(d => d.value === defaultValue.district)
    if (districtIndex === -1) return
    
    // 设置选中值
    pickerValue.value = [provinceIndex, cityIndex, districtIndex]
    selectedProvince.value = provinces.value[provinceIndex]
    selectedCity.value = cities.value[cityIndex]
    selectedDistrict.value = districts.value[districtIndex]
    
    // 触发change事件
    emit('change', {
      province: {
        value: selectedProvince.value.value,
        name: selectedProvince.value.name
      },
      city: {
        value: selectedCity.value.value,
        name: selectedCity.value.name
      },
      district: {
        value: selectedDistrict.value.value,
        name: selectedDistrict.value.name
      },
      areaText: `${selectedProvince.value.name} ${selectedCity.value.name} ${selectedDistrict.value.name}`,
      province_id: selectedProvince.value.value,
      city_id: selectedCity.value.value,
      region_id: selectedDistrict.value.value
    })
  } catch (error) {
    console.error('设置默认选中失败:', error)
  }
}

// 隐藏选择器
function onCancel() {
  emit('cancel')
}

// picker列发生变化时
async function onColumnChange(e) {
  try {
    const { column, value } = e.detail
    
    if (typeof column !== 'number' || typeof value !== 'number') {
      return
    }
    
    const newPickerValue = [...pickerValue.value]
    newPickerValue[column] = value
    pickerValue.value = newPickerValue
    
    if (column === 0) {
      // 省份改变，清空城市和区县
      if (provinces.value[value]) {
        // 重置选中的索引
        pickerValue.value[1] = 0
        pickerValue.value[2] = 0
        
        // 立即清空城市和区县数据
        cities.value = []
        districts.value = []
        pickerRange.value[1] = []
        pickerRange.value[2] = []
        
        // 强制更新picker显示
        forceUpdatePicker()
        
        // 异步加载新省份的城市数据
        await loadCities(provinces.value[value].value)
      }
    } else if (column === 1) {
      // 城市改变，清空区县
      if (cities.value[value]) {
        // 重置区县索引
        pickerValue.value[2] = 0
        
        // 清空区县数据
        districts.value = []
        pickerRange.value[2] = []
        
        // 强制更新picker显示
        forceUpdatePicker()
        
        // 获取当前选中的省份ID
        const currentProvinceId = provinces.value[pickerValue.value[0]]?.value
        // 异步加载新城市的区县数据
        await loadDistricts(currentProvinceId, cities.value[value].value)
      }
    }
    
    // 更新pickerRange
    pickerRange.value[1] = cities.value
    pickerRange.value[2] = districts.value
  } catch (error) {
    console.error('Column change error:', error)
  }
}

// picker确认选择
function onPickerChange(e) {
  try {
    const [provinceIndex, cityIndex, districtIndex] = e.detail.value
    
    if (typeof provinceIndex !== 'number' || typeof cityIndex !== 'number' || typeof districtIndex !== 'number') {
      return
    }
    
    const province = provinces.value[provinceIndex]
    const city = cities.value[cityIndex]
    const district = districts.value[districtIndex]
    
    if (province && city && district) {
      selectedProvince.value = province
      selectedCity.value = city
      selectedDistrict.value = district
      
      // 触发change事件
      emit('change', {
        province: {
          value: province.value,
          name: province.name
        },
        city: {
          value: city.value,
          name: city.name
        },
        district: {
          value: district.value,
          name: district.name
        },
        areaText: `${province.name} ${city.name} ${district.name}`,
        province_id: province.value,
        city_id: city.value,
        region_id: district.value
      })
    }
  } catch (error) {
    console.error('Picker change error:', error)
  }
}

// 加载省份数据（带幂等与并发保护）
async function loadProvinces() {
  try {
    if (provinces.value.length > 0 || isLoadingProvinces.value) return
    isLoadingProvinces.value = true

    const res = await API_INDEX_AREA_POST({ level: 1 })
    
    if (res && res.code === 1) {
      const provincesData = res.data.map(item => ({
        value: item.value,
        name: item.name
      }))
      
      provinces.value = provincesData
      
      // 初始化picker数据
      pickerRange.value[0] = provinces.value
      pickerRange.value[1] = []
      pickerRange.value[2] = []
      pickerValue.value = [0, 0, 0]
      
      // 默认加载第一个省份的城市数据
      if (provinces.value.length > 0) {
        await loadCities(provinces.value[0].value)
      }
    } else {
      console.error('省份数据格式错误:', res)
    }
  } catch (error) {
    console.error('加载省份失败:', error)
    uni.showToast({
      title: '地区数据加载失败，请重试',
      icon: 'none',
      duration: 2000
    })
  } finally {
    isLoadingProvinces.value = false
  }
}

// 加载城市数据
async function loadCities(provinceId) {
  if (!provinceId) return
  isLoadingCities.value = true
  try {
    const res = await API_INDEX_AREA_POST({ level: 2, province: provinceId })
    
    if (res && res.code === 1) {
      cities.value = res.data.map(item => ({
        value: item.value,
        name: item.name
      }))
      
      // 更新picker数据
      pickerRange.value[1] = cities.value
      pickerRange.value[2] = []
      
      // 默认加载第一个城市的区县数据
      if (cities.value.length > 0) {
        await loadDistricts(provinceId, cities.value[0].value)
      }
      
      // 强制更新picker显示
      forceUpdatePicker()
    } else {
      console.error('城市数据格式错误:', res)
    }
  } catch (error) {
    console.error('加载城市失败:', error)
  } finally {
    isLoadingCities.value = false
  }
}

// 加载区县数据
async function loadDistricts(provinceId, cityId) {
  if (!provinceId || !cityId) return
  isLoadingDistricts.value = true
  try {
    const res = await API_INDEX_AREA_POST({ level: 3, province: provinceId, city: cityId })
    
    if (res && res.code === 1) {
      districts.value = res.data.map(item => ({
        value: item.value,
        name: item.name
      }))
      
      // 更新picker数据
      pickerRange.value[2] = districts.value
      
      // 强制更新picker以确保显示
      forceUpdatePicker()
    } else {
      console.error('区县数据格式错误:', res)
    }
  } catch (error) {
    console.error('加载区县失败:', error)
  } finally {
    isLoadingDistricts.value = false
  }
}

// 强制更新picker数据
function forceUpdatePicker() {
  pickerRange.value = [
    [...provinces.value],
    [...cities.value],
    [...districts.value]
  ]
  pickerValue.value = [...pickerValue.value]
}

// 暴露方法给父组件
defineExpose({
  // 重置选择
  reset() {
    selectedProvince.value = null
    selectedCity.value = null
    selectedDistrict.value = null
    pickerValue.value = [0, 0, 0]
  },
  // 设置选中值
  async setValue(provinceId, cityId, districtId) {
    await setDefaultSelection({
      province: provinceId,
      city: cityId,
      district: districtId
    })
  },
  // 获取当前选中值
  getValue() {
    if (selectedProvince.value && selectedCity.value && selectedDistrict.value) {
      return {
        province: {
          value: selectedProvince.value.value,
          name: selectedProvince.value.name
        },
        city: {
          value: selectedCity.value.value,
          name: selectedCity.value.name
        },
        district: {
          value: selectedDistrict.value.value,
          name: selectedDistrict.value.name
        },
        areaText: `${selectedProvince.value.name} ${selectedCity.value.name} ${selectedDistrict.value.name}`,
        province_id: selectedProvince.value.value,
        city_id: selectedCity.value.value,
        region_id: selectedDistrict.value.value
      }
    }
    return null
  }
})
</script>

<style lang="scss" scoped>
.area-picker {
  .picker-row {
    width: 100%;
    height: 56rpx;
    background: #f5f6fa;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16rpx;
    margin-top: 8rpx;

    .picker-value {
      color: #333;
      font-size: 28rpx;
      width: 100%;
      &.placeholder {
        color: #999;
      }
    }

    .arrow {
      width: 32rpx;
      height: 32rpx;
    }
    
    &.picker-disabled {
      background: #f8f8f8;
      border-color: #e8e8e8;
      cursor: not-allowed;
      
      .picker-value {
        color: #999;
        &.placeholder {
          color: #999;
        }
      }
    }
  }
}
</style> 